var basePage = require('../../../common/BasePage');
var util = require('../../../utils/util');
Page({
    behaviors: [basePage],
    data: {
        checkMobile: false,
        pdcArr: [{}],
        /**每个商品需要支付的担保价格 */
        danbao_amount: 0,

        /**选中的地址数据 */
        addr: {
            addr_id: 0
        },
        /**品种确认图 */
        photoArr: [],

        /**选中的仓库信息 */
        warehouse: {},
        /**求购数量 */
        nums: '',
        /**单位 */
        unit: '',
        /**打包单位 */
        pack_unit: '',
        /**购买数量 */
        product_number: '',
        /**等级列表 */
        // levelArr: [],
        /**成熟度列表 */
        // maturityArr: [],
        textareaValue: '', //留言内容
        /**wxpay:微信支付,money:余额支付 coin:钱包支付 allin:通联支付*/
        // payType: 'allin',
        total_price: "0.00",
        /**可以发布求购时间提示 */
        tip: "",
        showPayType: false,
    },
    onLoad() {
        // this.setData({
        //     levelArr:JSON.parse(JSON.stringify( getApp().globalData.levelArr)),
        //     // maturityArr: getApp().globalData.maturityArr
        // });
        //获取押金金额
        this.request({
            url: this.data.host + '/home/index/config?wh_id=1&type=2',
        }, this.get_fee);
    },
    onShow() {
        let warehouse = getApp().globalData.warehouse;
        this.setData({
            warehouse,
        })
        // if (warehouse.wh_id == 10) {
        //     this.setData({
        //         payType: "wxpay",
        //     })
        // } else {
        //     this.setData({
        //         payType: "allin",
        //     })
        // }
        this.getPayType(warehouse.wh_id)
        wx.setNavigationBarTitle({
            title: '求购编辑(' + warehouse.title + ")",
        })
        let choose_pdc = wx.getStorageSync('choose_pdc');
        if (choose_pdc) {
            choose_pdc = JSON.parse(choose_pdc)
            let pdcArr = this.data.pdcArr;
            pdcArr[0] = choose_pdc;
            choose_pdc.levelArr = JSON.parse(JSON.stringify(getApp().globalData.levelArr));
            this.setData({
                pdcArr
            });
            wx.removeStorageSync('choose_pdc')
        }

    },
    /**获取金额 */
    get_fee(res) {
        this.setData({
            tip: "请在" + res.data.purchase_stime + "~" + res.data.purchase_ltime + "之间发起求购",
            danbao_amount: res.data.danbao_amount
        })
        // this.data.danbao_amount=res.data.danbao_amount;
    },
    /**选择等级 */
    level_check(e) {
        // console.log("level_check",e);
        let index = e.currentTarget.dataset.index;
        let i = e.currentTarget.dataset.i;

        this.setData({
            [`pdcArr[${index}].levelArr[${i}].checked`]: e.detail
        });
        this.update_total()
    },
    level_change(e) {
        // console.log("level_change",e);
        let index = e.currentTarget.dataset.index;
        let i = e.currentTarget.dataset.i;
        this.data.pdcArr[index].levelArr[i].nums = e.detail;
        console.log("pdcArr", this.data.pdcArr)
        // this.setData({
        //     [`pdcArr[${index}]levelArr[${i}].nums`]:e.detail
        // });
        this.update_total();
    },
    /**更新总价 */
    update_total() {
        let total_price = 0;
        this.data.pdcArr.map(pdc => {
            if (pdc.levelArr) {
                pdc.levelArr.map(val => {
                    // val.checked && val.nums * 1 ? total_price += val.nums * this.data.danbao_amount : "";
                    val.checked && val.nums * 1 ? total_price += val.nums * pdc.amount : "";
                })
            }

        });

        this.setData({
            total_price: total_price.toFixed(2)
        })
    },
    delete_pdc(e) {
        let index = e.currentTarget.dataset.index;
        this.data.pdcArr.splice(index, 1);
        if (this.data.pdcArr.length == 0) {
            this.data.pdcArr = [{}];
        }
        this.setData({
            pdcArr: this.data.pdcArr
        })
    },
    add_click() {
        this.data.pdcArr.push({
            title: "花2"
        });
        this.setData({
            pdcArr: this.data.pdcArr
        })
    },

    /**
     * 选中图片上传
     */
    afterRead(event) {
        console.log("afterRead", event);
        const file = event.detail.file;
        file.status = "uploading";
        this.data.photoArr.push(file);
        this.setData({
            photoArr: this.data.photoArr
        })
        let that = this;
        wx.uploadFile({
            filePath: file.url,
            name: 'image',
            url: this.data.host + '/home/upload/image',
            formData: {
                from: 'product'
            },
            success(res) {
                console.log("home/upload/image", res);
                if (res.statusCode != 200) {
                    file.status = "failed";
                    file.message = '上传失败';
                    return wx.showToast({
                        title: res.errMsg,
                        icon: 'none'
                    })
                }
                let resObj = JSON.parse(res.data)
                if (resObj.code) {
                    file.status = "failed";
                    file.message = '上传失败';
                    return wx.showToast({
                        title: resObj.msg,
                        icon: 'none'
                    })
                }
                file.photo = resObj.data.path;
                file.status = "done";
            },
            fail() {
                file.status = "failed";
                file.message = '上传失败';
            },
            complete() {
                that.setData({
                    photoArr: that.data.photoArr
                })
            }
        });
    },

    /**
     * 删除确认图
     */
    delete_photo({
        detail
    }) {
        this.data.photoArr.splice(detail.index, 1);
        this.setData({
            photoArr: this.data.photoArr
        })
    },

    //选择商品类型
    chooseGoods(e) {
        let index = e.currentTarget.dataset.index;
        // let queryStr = `goods=${this.data.goods}&site=${this.data.site}&goods_level=${this.data.goods_level}&goods_mature=${this.data.goods_mature}&goods_color=${this.data.goods_color}&goods_sku=${this.data.goods_sku}&start_time=${this.data.start_time}&end_time=${this.data.end_time}&send_time=${this.data.send_time}&textareaValue=${this.data.textareaValue}`;
        let that = this;
        let pdcArr = this.data.pdcArr;
        wx.navigateTo({
            url: "/pages/album/album?state=0",
            // url: '/pages/cls/qiugou_choosegoods/choose?wh_id=' + this.data.warehouse.wh_id,
            events: {
                choose_pdc: function (data) {
                    console.log("choose_pdc", data);
                    pdcArr[index] = data;
                    data.levelArr = JSON.parse(JSON.stringify(getApp().globalData.levelArr));
                    that.setData({
                        pdcArr
                    });
                }
            }
        })
    },
    //点击选择分站
    chooseSite() {
        this.setData({
            siteShow: true
        })
    },
    /**选择地址 */
    chooseAddr() {
        let that = this;
        wx.navigateTo({
            url: '/pages/addr/AddrList',
            events: {
                change_addr: function (data) {
                    console.log("change_addr", data);
                    that.setData({
                        addr: data.addr
                    })
                }
            }
        })
    },
    //分站选择上拉框关闭事件
    onClose() {
        this.setData({
            siteShow: false,
            start_timeShow: false,
            send_timeShow: false,
            end_timeShow: false
        });
    },


    //点击品种确认图
    // previewImage() {
    //     wx.previewImage({
    //         urls: ['../../test.jpg'] // 需要预览的图片http链接列表
    //     })
    // },
    //留言输入框输入事件
    textareaInput(e) {
        this.setData({
            textareaValue: e.detail.value
        })
    },
    onClose() {
        this.setData({
            showPayType: false
        });
    },
    //展示支付方式
    clickPayType() {
        let total_price = parseFloat(this.data.total_price.toString())
        if (!total_price) {
            return wx.showToast({
                title: '请先选择商品以及等级',
                icon: "none"
            })
        }
        this.setData({
            showPayType: true
        })
    },
    //选择支付方式
    onClick(event) {
        let name = event.currentTarget.dataset.name;
        this.setData({
            pay: name,
        })
    },
    submit_click(e) {
        // this.data.payType = e.currentTarget.dataset.pay;
        let total_price = parseFloat(this.data.total_price.toString())
        if (!total_price) {
            return wx.showToast({
                title: '请先选择商品以及等级',
                icon: "none"
            })
        }
        let products = [];
        this.data.pdcArr.map(pdc => {
            let item = {
                // product_id: pdc.product_id,
                product_id: pdc.photo_id,
                attr: []
            };
            if (pdc.levelArr) {
                pdc.levelArr.map(val => {
                    // val.checked&&val.nums?total_price+=val.nums*this.data.danbao_amount:"";
                    if (val.checked && val.nums * 1) {
                        item.attr.push({
                            level: val.value,
                            nums: util.replaceStr(val.nums),
                        })
                    }
                });
            }

            if (item.attr.length) {
                products.push(item);
            }
        });
        console.log("products", products)
        this.data.textareaValue = util.replaceStr(this.data.textareaValue)
        this.request({
            url: this.data.host + '/home/buy/purchase/handleNew',
            method: "POST",
            data: {
                products: JSON.stringify(products),
                wh_id: this.data.warehouse.wh_id,
                addr_id: this.data.addr.addr_id,
                intro: this.data.textareaValue
            }
        }, this.fb_ok);
    },

    /**
     * 发布成功
     */
    fb_ok(res) {
        console.log("fb_ok", res);
        this.setData({
            showPayType: false
        });
        let that = this;
        wx.showModal({
            title: '提示',
            showCancel: false,
            // cancelText: '暂不支付',
            confirmText: '支付定金',
            content: '此商品由' + that.data.warehouse.title + '发货，求购商品尽量采购，缺货会第一时间回复您，求购需要支付定金，多退少补。',
            success(res1) {
                if (res1.confirm) { //立即支付押金
                    that.req_pay(res.data)
                } else if (res1.cancel) { //暂不支付，前往我的求购页面
                    wx.switchTab({
                        url: '/pages/tabbar/my/my',
                    })
                }
            }
        })
    },
    /**请求支付参数 */
    req_pay(data) {
        // console.log("req_pay",data);
        this.request({
            url: this.data.host + '/home/payment/order',
            method: "POST",
            data: {
                order_id: data.order_id,
                code: this.data.pay
            }
        }, res => {
            console.log("res", res);
            this.setData({
                pdcArr: [{}],
                textareaValue: "",
                total_price: "0.00"
            })
            if (!res.data || !res.data.payInfo) {
                wx.showToast({
                    title: '发布成功',
                })
                setTimeout(() => {
                    wx.switchTab({
                        url: '/pages/tabbar/my/my',
                    })
                }, 1000);
                return;
            }
            if (this.data.pay == 'wxpay') { //调用微信支付
                wx.requestPayment({
                    ...res.data.pay_data,
                    success(res) {
                        wx.showToast({
                            title: '支付成功',
                        })

                    },
                    fail(err) {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        })
                        console.error('pay fail', err)
                    },
                    complete() {
                        wx.switchTab({
                            url: '/pages/tabbar/my/my',
                        })
                    }
                })
            } else if (this.data.pay == 'allin') {
                //通联支付
                var payInfo = res.data.payInfo
                if (payInfo) {
                    payInfo = JSON.parse(payInfo)
                    wx.requestPayment({
                        ...payInfo,
                        success(res) {
                            console.log('pay success', res);
                            wx.showToast({
                                title: '发布成功',
                            })
    
                        },
                        fail(err) {
                            wx.showToast({
                                title: '支付失败',
                            })
                            console.error('pay fail', err)
                        },
                        complete() {
                            wx.switchTab({
                                url: '/pages/tabbar/my/my',
                            })
                        }
                    })
                }else if(res.data.extraData){//跳转收银台小程序
                    var extraData=res.data.extraData

                    this.alinePay(extraData,this.pay_ok)

                }else{
                    wx.showToast({
                      title: '支付失败',
                      icon:"none"
                    })
                    setTimeout(()=>{
                        wx.switchTab({
                            url: '/pages/tabbar/my/my',
                        })
                    },500)
                }
                
            } else {
                wx.switchTab({
                    url: '/pages/tabbar/my/my',
                })
            }

        });
    },
    pay_ok(){
        wx.showToast({
            title: '发布成功',
        })
        wx.switchTab({
            url: '/pages/tabbar/my/my',
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: '源花采购',
            path: 'pages/cls/index/index?uid=' + +getApp().globalData.userInfo.uid,
            success: (res) => {
                console.log("转发成功", res);
            },
            fail: (res) => {
                console.log("转发失败", res);
            }
        }
    }

})